<?php
namespace Common\Logic;

/**
 * 房型预定处理逻辑
 * @modify trainyao 2016-04-29 创建
 */
class RoomTypeBookLogic extends \Common\Controller\BaseController {

    public function getInfo($hotelId) {
        return $this->__singleGet('_getInfo', array($hotelId));
    }

    /**
     * 获取房型预定上架信息
     * @modify trainyao 2016-04-29 创建
     * @modify trainyao 2016-06-28 增加房间权限判断
     * @param  integer   $hotelId   客栈ID
     * @return array              信息数组
     */
    protected function _getInfo($hotelId) {
        // 获取客栈所有房型
        $roomTypeModel = D('RoomType');
        $roomType = $roomTypeModel->getInfoByHotel($hotelId);

        // 判断是否需要校验房间权限,按照权限删除客栈房型
        if (MODULE_NAME != 'Extend') {
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);
                // 获取有权限房间所在的房型
                $roomInfoModel = D('RoomInfo');
                $multiRoom = count($roomAuthority) == 1 ? false : true;
                $roomAuthority = $roomInfoModel->getInfo($roomAuthority);
                if (!$multiRoom) {
                    $roomAuthority = array($roomAuthority);
                }
                $roomTypeAuthority = array_unique(array_column($roomAuthority, 'roomtype_id'));
                // 删除没有房间权限的房型
                foreach ($roomType as $index => $roomTypeItem) {
                    if (!in_array($roomTypeItem['id'], $roomTypeAuthority)) {
                        unset($roomType[$index]);
                    }
                }
                unset($roomTypeItem);
            }
        }
        if (empty($roomType)) {
            return array();
        }

        // 获取上架房型
        $roomTypeDetailModel = D('RoomTypeDetail');
        $roomTypeOnline = $roomTypeDetailModel->getInfoByHotel($hotelId);
        $roomTypeOnline = getArrayValueAsIndex($roomTypeOnline, 'roomtype_id');

        // 微预定价格日历
        $hotelRoomTypePriceModel = D('HotelRoomTypePrice');
        // 房型管理价格日历
        $RoomTypePriceModel = D('RoomTypePrice');

        // 处理数据
        foreach ($roomType as &$roomTypeItem) {
            if (isset($roomTypeOnline[$roomTypeItem['id']])) {
                $roomTypeItem['enable'] = $roomTypeOnline[$roomTypeItem['id']]['enable'] == ENABLE ? ENABLE : DISABLE;
                // 引用$roomTypeOnline数据
                $roomTypeItem['onlineData'] = &$roomTypeOnline[$roomTypeItem['id']];
                // 根据房型id和当天日期  从价格日历获取每个房型当天的价格
                // 当天价格获取分三种情况 先从微预定价格日历 如果没有再从房型管理价格日历  都没有就获取房型默认价格
                // 获取房型信息
                $roomTypeInfo = $roomTypeModel->getInfo($roomTypeItem['id']);
                // 房型默认价格
                $roomTypeDefaulPrice = $roomTypeInfo['price'];
                // 房型折扣值
                $discount = $roomTypeInfo['discount']/10;

                $roomTypePrice = $hotelRoomTypePriceModel->getBookPrice($roomTypeItem['id']);
                if (!empty($roomTypePrice)) {
                   $roomTypeItem['onlineData']['price'] = $roomTypePrice[0]['price'];
                } else {
                   $roomTypePrice = $RoomTypePriceModel->getBookPrice($roomTypeItem['id']);
                   if (!empty($roomTypePrice)) {
                       $roomTypeItem['onlineData']['price'] = number_format((($roomTypePrice[0]['price']*1000)/1000) * $discount, 2, '.', '');
                   } else {
                       $roomTypeItem['onlineData']['price'] = number_format((($roomTypeDefaulPrice*1000)/1000) * $discount, 2, '.', '');
                   }
                }
            } else {
                $roomTypeItem['enable'] = DISABLE;
                $roomTypeItem['onlineData'] = array();
            }
        }
        unset($roomTypeItem);

        // 获取房型图片
        $roomTypeOnlineIds = array_column($roomTypeOnline, 'roomtype_id');
        if (!empty($roomTypeOnlineIds)) {
            $roomTypePictureModel = D('RoomTypePicture');
            $roomTypePictureInfo = $roomTypePictureModel->getInfoByRoomType($roomTypeOnlineIds);
            if (!empty($roomTypePictureInfo)) {
                $roomTypePictureInfo = getArrayValueAsIndex($roomTypePictureInfo, 'roomtype_id', 'multi');
            }
            foreach ($roomType as &$roomTypeItem) {
                if (isset($roomTypePictureInfo[$roomTypeItem['id']])) {
                    $roomTypeItem['onlineData']['picture'] = $roomTypePictureInfo[$roomTypeItem['id']];
                } else {
                    $roomTypeItem['onlineData']['picture'] = array();
                }
            }
            unset($roomTypeItem);
        }

        return $roomType;
    }

    /**
     * 获取房型实时房态
     * 方法会抛异常
     * @modify trainyao    2016-06-23  创建
     * @modify wenhui      2016-12-21  修改返回price字段值，使用HotelRoomTypePrice表中的预定价格，增加门市价格
     * @modify zhangzhen   2017-3-15   增加尾房特卖价格
     * @param  integer     $hotelId    客栈ID
     * @param  string     $startDate  查询开始日期
     * @param  string     $endDate    查询结束日期
     * @param  array|null $roomTypeId 需要查询的房型ID,null默认查客栈全部房型
     * @param  mixin     $roomIds    房间ID,默认查全部
     * @return array              客栈信息数组,失败返回空数组
     *                             [{
     *                                 roomtype_id
     *                                 name
     *                                 price,coverimageurl...等等房型上架信息
     *                                 gallery 房型相册
     *                                 rest 房型剩余可预定数目
     *                                 room array( 房间实时房态
     *                                     id, name...等房间信息
     *                                     canBook 房间是否可预定
     *                                 )
     *                             }]
     */
    public function getRealtimeStatus($hotelId, $startDate, $endDate, array $roomTypeId = null, $roomIds = null) {
        $roomTypeDetailModel = D('RoomTypeDetail');
        if (is_null($roomTypeId)) {
            // 获取客栈所有上架房型
            $roomTypeDetail = $roomTypeDetailModel->getInfoByHotel($hotelId);
        } else {
            $roomTypeDetail = $roomTypeDetailModel->getInfoByHotelRoomType($hotelId, $roomTypeId);
            if (count($roomTypeId) == 1) {
                $roomTypeDetail = array($roomTypeDetail);
            }
        }
        if (empty($roomTypeDetail)) {
            return array();
        }
        $roomTypeId = array_column($roomTypeDetail, 'roomtype_id');
        // 筛选未上架的房型
        $roomTypeDetail = getArrayValueAsIndex($roomTypeDetail, 'enable', 'multi')[ENABLE];
        if (empty($roomTypeDetail)) {
            return array();
        }

        // 获取房型相册信息
        $roomTypePictureModel = D('RoomTypePicture');
        $roomTypePictureInfo = $roomTypePictureModel->getInfoByRoomType($roomTypeId);
        if (!empty($roomTypePictureInfo)) {
            $roomTypePictureInfo = getArrayValueAsIndex($roomTypePictureInfo, 'roomtype_id', 'multi');
        }

        // 获取房型信息
        $roomTypeModel = D('RoomType');
        $roomTypeInfo = $roomTypeModel->getInfo($roomTypeId);

        if (count($roomTypeId) == 1) {
            $roomTypeInfo = array($roomTypeInfo);
        }
        $roomTypeInfo = getArrayValueAsIndex($roomTypeInfo, 'id');
        
        if (is_null($roomIds)) {
            // 获取所有上架房型的房间
            $roomInfoModel = D('RoomInfo');
            $roomInfo = $roomInfoModel->getInfoByRoomType($hotelId, $roomTypeId);
            $roomIds = array_column($roomInfo, 'id');
        }

        // 获取时间段内,相关房间的订单
        $roomBookLogic = A('Common/RoomBook', 'Logic');
        try {
            $roomBookInfo = $roomBookLogic->getInfo($hotelId, $roomIds, $startDate, $endDate);
        } catch (\Exception $e) {
            throw $e;
            return;
        }

        $roomTypePriceModel = D('RoomTypePrice');
        foreach ($roomTypeDetail as $index => &$roomTypeDetailItem) {            
            if (! isset($roomTypeInfo[$roomTypeDetailItem['roomtype_id']])) {
                unset($roomTypeDetail[$index]);
                continue;
            }
            $roomTypeDetailItem['name'] = $roomTypeInfo[$roomTypeDetailItem['roomtype_id']]['name'];
            $roomTypeDetailItem['charityprice'] = $roomTypeInfo[$roomTypeDetailItem['roomtype_id']]['charityprice'];
            $roomTypeDetailItem['minusdiscount'] = $roomTypeInfo[$roomTypeDetailItem['roomtype_id']]['minusdiscount'];
            $roomTypeDetailItem['minustype'] = $roomTypeInfo[$roomTypeDetailItem['roomtype_id']]['minustype'];
            if (isset($roomTypePictureInfo[$roomTypeDetailItem['roomtype_id']])) {
                $roomTypeDetailItem['gallery'] = $roomTypePictureInfo[$roomTypeDetailItem['roomtype_id']];
            } else {
                $roomTypeDetailItem['gallery'] = array();
            }
            if (isset($roomBookInfo[$roomTypeDetailItem['roomtype_id']])) {
                $roomTypeDetailItem['rest'] = $roomBookInfo[$roomTypeDetailItem['roomtype_id']]['rest'];
                $roomTypeDetailItem['room'] = $roomBookInfo[$roomTypeDetailItem['roomtype_id']]['room'];
            } else {
                $roomTypeDetailItem['rest'] = 0;
                $roomTypeDetailItem['room'] = array();
            }

             // 房型折扣值
            $roomTypeDiscountInfo = $roomTypeModel->getInfo($roomTypeDetailItem['roomtype_id']);

            // 获取预定价格
            $roomTypePriceList = $roomTypePriceModel->getBookPrice($roomTypeDetailItem['roomtype_id'], $startDate);
            

            // 获取门市价格
            if (!empty($roomTypePriceList)) {
                $roomTypeDetailItem['shopPrice'] = number_format($roomTypePriceList[0]['price'], 2, '.', '');
            } else {
                $roomTypeDetailItem['shopPrice'] = number_format($roomTypeDiscountInfo['price'], 2, '.', '');
            }

            $getAllPrice =  getAllPrice($roomTypeDetailItem['roomtype_id'], $startDate, $endDate);
            $roomTypeDetailItem['price'] =  $getAllPrice['totalPrice'];
            // 获取在时间段$startDate, $endDate 预定价列表
            $roomTypeDetailItem['priceList'] =  $getAllPrice['priceList'];
            // 获取在时间段$startDate, $endDate 门市价列表
            $getAllshopPrice =  getAllPrice($roomTypeDetailItem['roomtype_id'], $startDate, $endDate, true);
            $roomTypeDetailItem['shopPriceList'] =  $getAllshopPrice['priceList'];
        }
        unset($index);
        unset($roomTypeDetailItem);
        return $roomTypeDetail;
    }

    /**
     * 上架多个房型
     * @modify trainyao 2016-04-29  创建
     * @param  integer   $hotelId    客栈id
     * @param  array   $roomTypeId 多个房型id
     * @return boolean                 执行结果
     */
    public function enableRoomType($hotelId, $roomTypeId) {
        $roomTypeInfo = $this->getInfo($hotelId);

        // 取出可上架的房型ID
        $canEnableRoomTypeId = array();
        $needAddInfoRoomTypeId = array();
        foreach ($roomTypeInfo as $roomTypeInfoItem) {
            if ($roomTypeInfoItem['enable'] == DISABLE) {
                array_push($canEnableRoomTypeId, $roomTypeInfoItem['id']);
                // 如果roomTypeDetail表内无数据,记录需要新增roomTypeDetail的id
                if (empty($roomTypeInfoItem['onlineData'])) {
                    array_push($needAddInfoRoomTypeId, $roomTypeInfoItem['id']);
                }
            }
        }
        unset($roomTypeInfoItem);
        if (empty($canEnableRoomTypeId)) {
            return true;
        }

        $canEnableRoomTypeId = array_values(array_intersect($canEnableRoomTypeId, $roomTypeId));

        // 前端传入id已经上架,考虑同步操作,返回ture
        if (empty($canEnableRoomTypeId)) {
            return true;
        }

        // 执行启用
        $roomTypeDetailModel = D('RoomTypeDetail');
        $roomTypeDetailModel->startTrans();
        $commit = true;

        // 添加初始启用的房型数据
        $needAddInfoRoomTypeId = array_values(array_intersect($needAddInfoRoomTypeId, $canEnableRoomTypeId));
        if (!empty($needAddInfoRoomTypeId)) {
            $enableResult = $roomTypeDetailModel->addInfo($hotelId, $needAddInfoRoomTypeId);
            if (empty($enableResult)) {
                $commit = false;
            }
        }

        // 修改已初始化数据的房型
        $canEnableRoomTypeId = array_values(array_diff($canEnableRoomTypeId, $needAddInfoRoomTypeId));
        if (!empty($canEnableRoomTypeId) && $commit) {
            $enableResult = $roomTypeDetailModel->saveEnableByRoomType($hotelId, $canEnableRoomTypeId, ENABLE);
            if (empty($enableResult)) {
                $commit = false;
            }
        }

        if ($commit) {
            $roomTypeDetailModel->commit();
            return true;
        } else {
            $roomTypeDetailModel->rollback();
            returnJson(500, 508);
            return false;
        }
    }

    /**
     * 下架多个房型
     * @modify trainyao 2016-04-29  创建
     * @param  integer   $hotelId    客栈id
     * @param  array   $roomTypeId 多个房型id
     * @return boolean                 执行结果
     */
    public function diableRoomType($hotelId, $roomTypeId) {
        $roomTypeInfo = $this->getInfo($hotelId);

        // 取出可下架的房型ID
        $canDisableRoomTypeId = array();
        foreach ($roomTypeInfo as $roomTypeInfoItem) {
            if ($roomTypeInfoItem['enable'] == ENABLE) {
                array_push($canDisableRoomTypeId, $roomTypeInfoItem['id']);
            }
        }
        unset($roomTypeInfoItem);
        if (empty($canDisableRoomTypeId)) {
            return true;
        }

        $roomTypeId = array_values(array_intersect($canDisableRoomTypeId, $roomTypeId));

        // 前端传入id已经上架,考虑同步操作,返回ture
        if (empty($roomTypeId)) {
            return true;
        }

        // 执行启用
        $roomTypeDetailModel = D('RoomTypeDetail');
        $enableResult = $roomTypeDetailModel->saveEnableByRoomType($hotelId, $roomTypeId, DISABLE);
        if (empty($enableResult)) {
            returnJson(500, 508);
            return false;
        }
        return true;
    }


    /**
     * 保存上架房型信息
     * @modify trainyao 2016-05-03   创建
     * @param  integer   $hotelId     客栈ID
     * @param  integer   $roomTypeId  房型ID
     * @param  string   $price       房型价格
     * @param  string   $description 房型描述
     * @param  string   $coverImageUrl  封面图片url
     * @param  array   $url         房型展示图片url信息数组
     * @return boolean                  执行结果
     */
    public function saveInfo($hotelId, $roomTypeId, $price = null, $description = null, $coverImageUrl = null, $url = null) {
        $roomTypeDetailModel = D('RoomTypeDetail');
        $roomTypeDetailModel->startTrans();
        $commit = true;

        // 先查询是否已经插入数据,不存在先新建数据
        $roomTypeDetail = $roomTypeDetailModel->getInfoByHotel($hotelId);
        $roomTypeDetail =getArrayValueAsIndex($roomTypeDetail, 'roomtype_id');
        if (!isset($roomTypeDetail[$roomTypeId])) {
            $saveResult = $roomTypeDetailModel->addInfo($hotelId, $roomTypeId, DISABLE);
            if (empty($saveResult)) {
                $commit = false;
            }
        }

        // 保存基本信息
        if ($commit && (!is_null($price) || !is_null($description) || !is_null($coverImageUrl))) {
            $saveResult = $roomTypeDetailModel->saveInfo($hotelId, $roomTypeId, $price, $description, $coverImageUrl);
            if (empty($saveResult)) {
                $commit = false;
            }
        }

        // 保存相册
        if ($commit && !is_null($url)) {
            $roomTypeDetail = $this->getInfo($hotelId);
            $roomTypeDetail = getArrayValueAsIndex($roomTypeDetail, 'id');
            $roomTypeUrlToDelete = $roomTypeDetail[$roomTypeId]['onlineData']['picture'];

            // 处理传入数据
            $urlToAdd = array();
            foreach ($url as $urlItem) {
                $urlToAdd[$urlItem] = 1;
            }
            unset($urlItem);
            unset($url);

            // 取出数据库内存在,也传进来的url
            foreach ($roomTypeUrlToDelete as $index => $roomTypeUrlToDeleteItem) {
                if (isset($urlToAdd[$roomTypeUrlToDeleteItem['name']])) {
                    unset($roomTypeUrlToDelete[$index]);
                    unset($urlToAdd[$roomTypeUrlToDeleteItem['name']]);
                }
            }
            unset($roomTypeUrlToDeleteItem);

            $roomTypePictureModel = D('RoomTypePicture');
            // 删除图册
            if (!empty($roomTypeUrlToDelete)) {
                $roomTypeUrlToDelete = array_column($roomTypeUrlToDelete, 'id');
                $saveResult = $roomTypePictureModel->deleteInfo($roomTypeUrlToDelete);
                if (empty($saveResult)) {
                    $commit = false;
                }
            }

            // 插入图册
            if ($commit && !empty($urlToAdd)) {
                $urlToAdd = array_keys($urlToAdd);
                $saveResult = $roomTypePictureModel->addInfo($roomTypeId, $urlToAdd);
                if (empty($saveResult)) {
                    $commit = false;
                }
            }
        }

        if ($commit) {
            $roomTypeDetailModel->commit();
            return true;
        } else {
            $roomTypeDetailModel->rollback();
            returnJson(500, 506);
            return false;
        }
    }

    /**
     * 检查一个或多个房型是否可以预定
     * 该方法不会抛异常
     * @modify trainyao 2016-05-05  创建
     * @param  integer   $hotelId   
     * @param  array   $roomTypeId 一个或多个房型ID
     * @return boolean                 是否可以预定
     */
    public function checkBookable($hotelId, array $roomTypeId) {
        // 检查房型ID是否在客栈内
        $roomTypeModel = D('RoomType');
        $roomTypeInfo = $roomTypeModel->getInfoByHotel($hotelId);
        $roomTypeIds = array_column($roomTypeInfo, 'id');
        if (empty($roomTypeIds)) {
            return false;
        }

        foreach ($roomTypeId as $roomTypeIdItem) {
            if (!in_array($roomTypeIdItem, $roomTypeIds)) {
                return false;
            }
        }
        unset($roomTypeIdItem);

        // 检查房型ID是否已经上架
        $roomTypeDetailModel = D('RoomTypeDetail');
        $roomTypeDetail = $roomTypeDetailModel->getInfoByHotel($hotelId);
        $roomTypeIds = array();
        foreach ($roomTypeDetail as $roomTypeDetailItem) {
            if ($roomTypeDetailItem['enable'] == ENABLE) {
                array_push($roomTypeIds, $roomTypeDetailItem['roomtype_id']);
            }
        }
        unset($roomTypeDetailItem);
        if (empty($roomTypeIds)) {
            return false;
        }

        foreach ($roomTypeId as $roomTypeIdItem) {
            if (!in_array($roomTypeIdItem, $roomTypeIds)) {
                return false;
            }
        }
        unset($roomTypeIdItem);
        
        return true;
    }

    /**
     * 检查房间是否与房型对应
     * 方法不会抛异常
     * @modify trainyao 2016-05-05  创建
     * @modify wenhui 2017-02-14  检查多个房间id
     * @param  integer   $hotelId    客栈ID
     * @param  integer   $roomTypeId 房型ID
     * @param  array   $roomId     房间ID
     * @return boolean               是否对应
     */
    public function checkRoomInRoomType($hotelId, $roomTypeId, $roomId) {
        $roomInfoModel = D('RoomInfo');
        $roomInfo = $roomInfoModel->getInfoByRoomType($hotelId, $roomTypeId);
        $roomIds = array_column($roomInfo, 'id');

        foreach ($roomId as $roomIdItiem) {
            $return = in_array($roomIdItiem, $roomIds) ? true : false;
            if (!$return) {
                return false;
            }
        }

        return true;
    }

    /**
     * 根据房型id获取
     * @modify trainyao 2016-04-29  创建
     * @param  mixin   $roomTypeId 客栈ids
     * @return array               房型数据
     */
    public function getInfoByRoomType($roomTypeId) {
        $RoomTypePictureModel = D('RoomTypePicture');
        $roomPicture = $RoomTypePictureModel->getInfoByRoomType($roomTypeId);
        return empty($roomPicture) ? false : $roomPicture;
    }

    /**
     * 根据房型id，url 获取一条记录
     * @modify wenhui 2016-11-29  创建
     * @param  int   $roomTypeId 房型id
     * @param  string   $url
     * @return array               房型数据
     */
    public function getImageInfo($roomTypeId = null, $url =null) {
        $RoomTypePictureModel = D('RoomTypePicture');
        $roomInfo = $RoomTypePictureModel->getImageInfo($roomTypeId, $url);
        return $roomInfo === false ? false : $roomInfo;
    }

    /**
     * 根据房型图片id删除一条记录
     * @modify wenhui 2016-11-29  创建
     * @param  int   $imageId 图片id
     */
    public function deleteRoomTypeImage($roomTypePictureId) {
        $RoomTypePictureModel = D('RoomTypePicture');
        $isDelete = $RoomTypePictureModel->deleteInfo($roomTypePictureId);
        return $isDelete === false ? false : true;
    }
}
